package com.test.view;

import com.test.dao.StudentDao;
import com.test.model.Student;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class UserStudentView extends JFrame {

    public JPanel thePanel;

    private JPanel jPAddStudent;
    private JPanel jPStudentManager ;

    private JPanel jPButton ;

    //设置label
    private JLabel jLnumber_student;  //学生姓名
    private JTextField txtnumber_student; //学生姓名文本框
    private JLabel jLstudent_name;
    private JTextField txtstudent_name;
    private JLabel jLsex;
    private JTextField txtsex;
    private JLabel jLbirthday;
    private JTextField txtbirthday;
    private JLabel jLage;
    private JTextField txtage;
    private JLabel jLcollege;
    private JTextField txtcollege;
    private JLabel jLmajor;
    private JTextField txtmajor;
    private JLabel jLmajor_type;
    private JTextField txtmajor_type;
    private JLabel jLclase_name;
    private JTextField txtclase_name;

    //数据表
    private JTable jTStudent;

    //学生操作按钮
    private JButton jbAdd,jbedit ,jbDeleteSelected;  //新增，删除，删除选中项

    private JLabel jLFindKeyword;  //查找关键字
    private JTextField txtFindKeyword; //查找关键字
    private JComboBox jcbFindKeyword; //查找关键字
    private JLabel jLSortKeyword;  //排序关键字
    private JTextField txtSortKeyword; //查找关键字
    private JComboBox jcbSortKeyword; //查找关键字

    private List<Student> studentList = new ArrayList<Student>();

    StudentDao stuDao = new StudentDao();

    /** Creates new form MainFrm */
    public UserStudentView() {
        initComponents();
        this.setSize(800, 360);
        this.beginStudentList();
        this.fillTable();
    }

    /**
     * 页面初始话
     */
    private void initComponents() {

        jPAddStudent = new JPanel();  //学生新增页面
        jPStudentManager = new JPanel();  //学生管理页面

        jPButton = new JPanel();  //按钮框
        jPButton.setLayout(new GridLayout(3,2));
        thePanel = new JPanel();

        thePanel.setLayout(new GridLayout(1,2));
        thePanel.add(jPAddStudent);
        thePanel.add(jPStudentManager);

        thePanel.setSize(500,360);
        jPAddStudent.setSize(100,360);
        jPStudentManager.setSize(400,360);

        //增加新增学生的页面
        jLnumber_student = new JLabel("学号");
        jLstudent_name = new JLabel("姓名");
        jLsex = new JLabel("性别");
        jLbirthday = new JLabel("生日");
        jLage = new JLabel("年龄");
        jLcollege = new JLabel("学院");
        jLmajor = new JLabel("所在系");
        jLmajor_type = new JLabel("所在系类别");
        jLclase_name = new JLabel("班级");
        jLnumber_student.setHorizontalAlignment(JLabel.RIGHT);
        jLstudent_name.setHorizontalAlignment(JLabel.RIGHT);

        jLsex.setHorizontalAlignment(JLabel.RIGHT);
        jLbirthday.setHorizontalAlignment(JLabel.RIGHT);
        jLage.setHorizontalAlignment(JLabel.RIGHT);
        jLcollege.setHorizontalAlignment(JLabel.RIGHT);
        jLmajor.setHorizontalAlignment(JLabel.RIGHT);
        jLmajor_type.setHorizontalAlignment(JLabel.RIGHT);
        jLclase_name.setHorizontalAlignment(JLabel.RIGHT);

        jLnumber_student.setSize(40, 30);
        jLstudent_name.setSize(40, 30);
        jLsex.setSize(40, 30);
        jLbirthday.setSize(40, 30);
        jLage.setSize(40, 30);
        jLcollege.setSize(40, 30);
        jLmajor.setSize(40, 30);
        jLmajor_type.setSize(40, 30);
        jLclase_name.setSize(40, 30);


        txtnumber_student = new JTextField();
        txtstudent_name = new JTextField();
        txtsex = new JTextField();
        txtbirthday = new JTextField();
        txtage = new JTextField();
        txtcollege = new JTextField();
        txtmajor = new JTextField();
        txtmajor_type = new JTextField();
        txtclase_name = new JTextField();

        txtnumber_student.setSize(70, 30);
        txtstudent_name.setSize(70, 30);
        txtsex.setSize(70, 30);
        txtbirthday.setSize(70, 30);
        txtage.setSize(70, 30);
        txtcollege.setSize(70, 30);
        txtmajor.setSize(70, 30);
        txtmajor_type.setSize(70, 30);
        txtclase_name.setSize(70, 30);

        //将新增学生页面添加
        jPAddStudent.setLayout(new GridLayout(7,2));
        jPAddStudent.add(jLnumber_student);
        jPAddStudent.add(txtnumber_student);
        jPAddStudent.add(jLstudent_name);
        jPAddStudent.add(txtstudent_name);
        jPAddStudent.add(jLsex);
        jPAddStudent.add(txtsex);

        jPAddStudent.add(jLage);
        jPAddStudent.add(txtage);
        jPAddStudent.add(jLcollege);
        jPAddStudent.add(txtcollege);
        jPAddStudent.add(jLmajor);
        jPAddStudent.add(txtmajor);

        jPAddStudent.add(jLclase_name);
        jPAddStudent.add(txtclase_name);

        //数据查看页面
        jPStudentManager.setLayout(new GridLayout(3,1,0,0));

        //学生表
        jTStudent = new JTable();
        jTStudent.setModel(new DefaultTableModel(new Object[][] {}, new String[] {"学号", "姓名", "性别",
                "年龄", "学院", "所在系", "班级" }) {
            boolean[] canEdit = new boolean[] { false, false, false, false, false, false, false };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });

        jTStudent.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                bookTypeTableMousePressed(evt);
            }
        });

        jTStudent.setVisible(true);
        jTStudent.setSize(400,40);

        //jpTable.add(jTcomputerTable);
        //jP_Browse.add(jpTable);
        JTableHeader jTableHeader = jTStudent.getTableHeader();
        jTableHeader.setSize(400,240);

        jPStudentManager.add(jTableHeader);
        jPStudentManager.add(jTStudent);
        jPStudentManager.setPreferredSize(new Dimension(300, 300));

        //设置操作按钮
        jbAdd = new JButton("添加");
        jbAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAdd(evt);
            }
        });

        jbedit = new JButton("修改");
        jbedit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbedit(evt);
            }
        });

        jbDeleteSelected = new JButton("删除选中项");
        jbDeleteSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbDeleteSelect(evt);
            }
        });

        jLFindKeyword = new JLabel("查找关键字");  //查找关键字
        txtFindKeyword = new JTextField(); //查找关键字
        jLSortKeyword = new JLabel("排序关键字");  //排序关键字
        txtSortKeyword = new JTextField(); //查找关键字

        jcbFindKeyword = new JComboBox();
        jcbFindKeyword.addItem("学号");
        jcbFindKeyword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                findEvent(evt);
            }
        });

        jcbSortKeyword = new JComboBox();
        jcbSortKeyword.addItem("姓名");
        jcbSortKeyword.addItem("年龄");
        jcbSortKeyword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sortEvent(evt);
            }
        });
        jPButton.add(jLFindKeyword);
        jPButton.add(jcbFindKeyword);
        //jPButton.add(jbedit);
        jPButton.setSize(400,80);

        jPStudentManager.add(jPButton);

        this.add(thePanel);
    }

    /*
     * 学生信息表里的鼠标监听
     * @param evt
     */
    private void bookTypeTableMousePressed(java.awt.event.MouseEvent evt) {
        // 获取选中的行
        int row = jTStudent.getSelectedRow();

        txtnumber_student.setText((String)jTStudent.getValueAt(row, 0));
        txtstudent_name.setText((String)jTStudent.getValueAt(row, 1));
        txtsex.setText((String)jTStudent.getValueAt(row, 2));

        txtage.setText((String)jTStudent.getValueAt(row, 3));
        txtcollege.setText((String)jTStudent.getValueAt(row, 4));
        txtmajor.setText((String)jTStudent.getValueAt(row, 5));

        txtclase_name.setText((String)jTStudent.getValueAt(row, 6));



    }

    /**
     * 添加按钮的鼠标监听
     * @param evt
     */
    private void jbAdd(java.awt.event.ActionEvent evt) {
        System.out.println("---添加按钮");

        String number_student = txtnumber_student.getText() ;
        String student_name = txtstudent_name.getText() ;
        String sex = txtsex.getText() ;
        String birthday = txtbirthday.getText() ;
        String age = txtage.getText() ;
        if("".equals(age.trim())){
            age = "0" ;
        }
        String college  = txtcollege.getText();
        String major = txtmajor.getText() ;
        String major_type = txtmajor_type.getText() ;
        String clase_name = txtclase_name.getText() ;

        Student stu = new Student(number_student, student_name, sex, birthday, age, college,major,major_type,clase_name );
        //保存新增学生
        this.studentList.add(stu);

        //数据库里新增学生
        try {
            stuDao.AddStudents(number_student, student_name, sex, birthday, age, college, major, major_type, clase_name);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //修改学生列表
        this.fillTable();

    }

    /**
     * 删除选中项按钮的监听
     * @param evt
     */
    private void jbDeleteSelect(java.awt.event.ActionEvent evt) {
        System.out.println("---删除选中项");
        // 获取选中的行
        int row = jTStudent.getSelectedRow();
        int allrow = jTStudent.getRowCount();
        String number_student ;
        String student_name ;
        String sex ;
        String birthday ="";
        String age ;
        String college  ;
        String major ;
        String major_type = "";
        String clase_name ;


        List<Student> thestudentList = new ArrayList<Student>();

        //将删除后的列表存储
        for(int i=0 ;i< allrow ;i++){
            number_student = (String)jTStudent.getValueAt(i, 0);
            student_name = (String)jTStudent.getValueAt(i, 1);
            sex = (String)jTStudent.getValueAt(i, 2);
            age = (String)jTStudent.getValueAt(i, 3);
            college  = (String)jTStudent.getValueAt(i, 4);
            major = (String)jTStudent.getValueAt(i, 5);
            clase_name = (String)jTStudent.getValueAt(i, 6);
            Student stu = new Student(number_student,student_name,  sex, birthday, age, college, major, major_type,clase_name);

            if(i == row ){
                //将该项从数据库中删除
                try {
                    stuDao.DeleteStudentsById(number_student);
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                thestudentList.add(stu);
            }
        }
        //新的学生列表覆盖原有学生列表
        this.studentList = thestudentList ;

        //修改学生列表
        this.fillTable();
    }

    /**
     * 删除选中项按钮的监听
     * @param evt
     */
    private void jbedit(java.awt.event.ActionEvent evt) {
        System.out.println("---修改");
        // 获取选中的行
        int row = jTStudent.getSelectedRow();
        int allrow = jTStudent.getRowCount();
        String number_student ;
        String student_name ;
        String sex ;
        String birthday = "" ;
        String age ;
        String college  ;
        String major ;
        String major_type= "" ;
        String clase_name ;


        List<Student> thestudentList = new ArrayList<Student>();

        //将删除后的列表存储
        for(int i=0 ;i< allrow ;i++){
            number_student = (String)jTStudent.getValueAt(i, 0);
            student_name = (String)jTStudent.getValueAt(i, 1);
            sex = (String)jTStudent.getValueAt(i, 2);
            age = (String)jTStudent.getValueAt(i, 3);
            college  = (String)jTStudent.getValueAt(i, 4);
            major = (String)jTStudent.getValueAt(i, 5);
            clase_name = (String)jTStudent.getValueAt(i, 6);
            Student stu = new Student(number_student,student_name,  sex, birthday, age, college, major, major_type,clase_name);

            if(i == row ){
                //将该项从数据库中删除
                ;
            } else {
                thestudentList.add(stu);
            }
        }

        number_student = txtnumber_student.getText() ;
        student_name = txtstudent_name.getText() ;
        sex = txtsex.getText() ;
        birthday = txtbirthday.getText() ;
        age = txtage.getText() ;
        if("".equals(age.trim())){
            age = "0" ;
        }
        college  = txtcollege.getText();
        major = txtmajor.getText() ;
        major_type = txtmajor_type.getText() ;
        clase_name = txtclase_name.getText() ;

        Student stu = new Student(number_student, student_name, sex, birthday, age, college,major,major_type,clase_name );
        thestudentList.add(stu);

        //保存到数据库
        try {
            stuDao.UpdateStudentsById(number_student, student_name, sex, birthday, age, college, major, major_type, clase_name);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //新的学生列表覆盖原有学生列表
        this.studentList = thestudentList ;

        //修改学生列表
        this.fillTable();
    }

    /**
     * 查找筛选框
     * @param evt
     */
    private void findEvent(java.awt.event.ActionEvent evt) {
        System.out.println("---查找筛选框");
        String findStr = (String) jcbFindKeyword.getSelectedItem();
        String sortStrName = "学号" ;
        System.out.println("--筛选字段 " + findStr );

        int allrow = jTStudent.getRowCount();

        String stuName ;
        String birthday ;
        String sex ;
        String province ;
        String city ;
        String college  ;
        String major ;
        String stuNumber ;
        String tuanyaun ;
        String thestuNumber = txtnumber_student.getText() ;  //姓名
        String thebirthday = txtbirthday.getText();

        boolean selected = false ;

        List<Student> selectedStudentList = new ArrayList<Student>();

        for(Student stu : studentList){
            stuName = stu.getNumber_student();
            birthday = stu.getBirthday();

            selected = false ;

            //判断按学生名称筛选还是按出生日期筛选
            if(sortStrName == findStr ){
                if(thestuNumber.equals(stuName)){
                    selected = true ;
                }
            }

            if(selected){
                selectedStudentList.add(stu);
            }
        }

        //将数据更新
        this.fillTable(selectedStudentList);
    }

    /**
     * 排序框
     * @param evt
     */
    private void sortEvent(java.awt.event.ActionEvent evt) {
        System.out.println("---排序选中项");
        String sortStr = (String) jcbSortKeyword.getSelectedItem();
        System.out.println("== " + sortStr);
        String sortStrName = "姓名" ;
        String sortStrBirthday = "出生日期" ;

        //进行排序操作

        if(sortStrName.equals(sortStr)){
            Collections.sort(this.studentList,new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    return o1.getStudent_name().compareTo(o2.getStudent_name()) ;
                }
            });
        } else {
            Collections.sort(this.studentList,new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    return o1.getBirthday().compareTo(o2.getBirthday()) ;
                }
            });
        }

        //设置表单数据
        this.fillTable();
    }

    private void beginStudentList() {

        this.studentList = new ArrayList<Student>();


        try {
            this.studentList = stuDao.getAllStudents();
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 设置CompuerTable
     * @param bookType
     */
    private void fillTable() {
        DefaultTableModel dtm = (DefaultTableModel) jTStudent.getModel();
        dtm.setRowCount(0);
        try {

            for(Student stu : studentList){
                //设置每一行
                Vector v = new Vector();
                v.add(stu.getNumber_student());
                v.add(stu.getStudent_name());
                v.add(stu.getSex());
                v.add(stu.getAge());
                v.add(stu.getCollege());
                v.add(stu.getMajor());
                v.add(stu.getClase_name());
                dtm.addRow(v);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 设置CompuerTable
     * @param bookType
     */
    private void fillTable(List<Student> thestudentList) {
        DefaultTableModel dtm = (DefaultTableModel) jTStudent.getModel();
        dtm.setRowCount(0);
        try {

            for(Student stu : thestudentList){
                //设置每一行
                Vector v = new Vector();
                v.add(stu.getNumber_student());
                v.add(stu.getStudent_name());
                v.add(stu.getSex());
                v.add(stu.getBirthday());
                v.add(stu.getAge());
                v.add(stu.getCollege());
                v.add(stu.getMajor());
                v.add(stu.getMajor_type());
                v.add(stu.getClase_name());
                dtm.addRow(v);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UserStudentView().setVisible(true);
            }
        });
    }

}

